import router from '@/router'
import store from '@/store'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
window.addRouteFlag = false // 刷新时需要重新加载异步路由
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = store.getters.token

  if (hasToken) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      if (window.addRouteFlag) {
        next()
        NProgress.done()
      } else {
        try {
          // const accessRoutes = await store.dispatch('permission/generateRoutes')
          // accessRoutes.forEach(item => {
          //   if (item.path === '*') {
          //     item.path = '/:pathMatch(.*)*'
          //   }
          //   router.addRoute(item)
          // })

          window.addRouteFlag = true
          next({ ...to, replace: true })
          NProgress.done()
        } catch (error) {
          // 报错时退出
          await store.dispatch('user/logout')
          ElMessage.error('Has Error')
          if (import.meta.env.MODE === 'production') {
            window.location.href = `${window.location.origin}/login`
          } else {
            window.location.href = `${import.meta.env.VUE_APP_BASE}/login`
          }
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
      NProgress.done()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

